package com.dog.basics.service.mtkj.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.api.mtkj.ApiBasketAddDto;
import com.dog.basics.bean.dto.api.mtkj.ApiBasketEditDto;
import com.dog.basics.bean.dto.api.mtkj.ApiShoppingCarVo;
import com.dog.basics.bean.model.mtkj.MtBasket;
import com.dog.basics.bean.model.mtkj.MtGoods;
import com.dog.basics.bean.model.mtkj.MtGoodsSku;
import com.dog.basics.bean.model.mtkj.MtShopping;
import com.dog.basics.bean.vo.api.mtkj.ApiBasketVo;
import com.dog.basics.dao.common.DogUserMapper;
import com.dog.basics.dao.mtkj.MtBasketMapper;
import com.dog.basics.dao.mtkj.MtGoodsMapper;
import com.dog.basics.dao.mtkj.MtGoodsSkuMapper;
import com.dog.basics.dao.mtkj.MtShoppingMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.mtkj.IMtBasketService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author wph
 * @since 2020-11-09
 */
@Service
@AllArgsConstructor
public class MtBasketServiceImpl extends ServiceImpl<MtBasketMapper, MtBasket> implements IMtBasketService {
    private final MtGoodsMapper mtGoodsMapper;
    private final DogUserMapper dogUserMapper;
    private final MtGoodsSkuMapper mtGoodsSkuMapper;
    private final MtShoppingMapper mtShoppingMapper;

    /**
     * @Description: 分页购物车列表
     * @Param: BasketFromDto
     * @return: IPage<BasketVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public List<ApiShoppingCarVo> getPageList() {
        List<MtBasket> oldlist = this.list(Wrappers.<MtBasket>lambdaQuery().eq(MtBasket::getUserId, SecurityUtils.getUser().getUserId()));
        List<ApiBasketVo> list = oldlist.stream().map(e -> {
            ApiBasketVo apiBasketVo = new ApiBasketVo();
            BeanUtil.copyProperties(e, apiBasketVo);
            MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(e.getSkuId());
            apiBasketVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            apiBasketVo.setPrice(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getPrice() : BigDecimal.ZERO);
            apiBasketVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
            apiBasketVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
            return apiBasketVo;
        }).collect(Collectors.toList());
        //进行购物车查订单处理
        List<ApiShoppingCarVo> orderCarIds = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            Map<Long, List<ApiBasketVo>> categoryMap = list.stream().collect(Collectors.groupingBy(ApiBasketVo::getShopId));
            categoryMap.forEach((k, v) -> {
                ApiShoppingCarVo apiShoppingCarVo = new ApiShoppingCarVo();
                apiShoppingCarVo.setShopId(k);
                MtShopping mtShopping = mtShoppingMapper.selectById(k);
                apiShoppingCarVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
                apiShoppingCarVo.setPickAddress(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getPickAddress() : "");
                apiShoppingCarVo.setApiBasketVo(v);
                apiShoppingCarVo.setUserName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getRealName() : "");
                apiShoppingCarVo.setMobile(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getMobile() : "");
                apiShoppingCarVo.setSendPrice(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getSendPrice() : BigDecimal.ZERO);

                orderCarIds.add(apiShoppingCarVo);
            });
        }
        return orderCarIds;
    }

    /**
     * @Description: 增加购物车
     * @Param: BasketAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveObj(ApiBasketAddDto obj) {
        Validator.validateTrue(obj.getBasketCount() > 0, "数量不正确!");
        //判断商品是否存在
        MtGoods mtGoods = mtGoodsMapper.selectById(obj.getGoodsId());
        Validator.validateNotNull(mtGoods, "商品不存在!");
        //判断商品的状态
        Validator.validateTrue(mtGoods.getStatus() == 1, "商品不再上架状态!");
        //判断SKU是否存在
        MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(obj.getSkuId());
        Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
        Validator.validateTrue(mtGoodsSku.getStock() > 0, "商品库存数量不足!");
        //判断库存是否充足
        Validator.validateTrue(mtGoodsSku.getStock() >= obj.getBasketCount(), "商品库存数量不足!");
        //减少库存
//        mtGoodsSku.setStock(mtGoodsSku.getStock() - obj.getBasketCount());
  //      Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存减少失败!");
//查询购物车是否已经存在
        List<MtBasket> list = this.list(Wrappers.<MtBasket>lambdaQuery().eq(ObjectUtil.isNotNull(obj.getSkuId()), MtBasket::getSkuId, obj.getSkuId()).eq(ObjectUtil.isNotNull(obj.getGoodsId()), MtBasket::getGoodsId, obj.getGoodsId()).eq(MtBasket::getUserId, SecurityUtils.getUser().getUserId()));
        if (CollUtil.isNotEmpty(list)) {
            MtBasket dogBasket = list.get(0);
            Validator.validateTrue(dogBasket.getBasketCount() + obj.getBasketCount() > 0, "商品库存数量不足!");
            dogBasket.setBasketCount(dogBasket.getBasketCount() + obj.getBasketCount());
            Validator.validateTrue(mtGoodsSku.getStock() >= dogBasket.getBasketCount(), "商品库存数量不足!");
            dogBasket.setUpdateTime(DateUtil.currentSeconds());
            dogBasket.setUpdateBy(SecurityUtils.getUser().getUserId());
            Validator.validateTrue(this.updateById(dogBasket), "加入购物车失败!");
        } else {
            MtBasket dogBasket = new MtBasket();
            BeanUtil.copyProperties(obj, dogBasket);
            dogBasket.setShopId(mtGoods.getShopId());
            dogBasket.setBasketDate(DateUtil.currentSeconds());
            dogBasket.setUserId(SecurityUtils.getUser().getUserId());
            dogBasket.setCreateTime(DateUtil.currentSeconds());
            dogBasket.setCreateBy(SecurityUtils.getUser().getUserId());
            Validator.validateTrue(this.save(dogBasket), "加入购物车失败!");
        }
        return Boolean.TRUE;
    }

    /**
     * @Description: 修改购物车
     * @Param: BasketEditDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editObj(ApiBasketEditDto obj) {
        MtBasket dogBasket = this.getById(obj.getId());
        Validator.validateNotNull(dogBasket, "无此数据");
        //判断商品是否存在
        MtGoods mtGoods = mtGoodsMapper.selectById(obj.getGoodsId());
        Validator.validateNotNull(mtGoods, "商品不存在!");
        //判断商品的状态
        Validator.validateTrue(mtGoods.getStatus() == 1, "商品不再上架状态!");
        //判断SKU是否存在
        MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(obj.getSkuId());
        Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
        Validator.validateTrue(mtGoodsSku.getStock() > 0, "商品库存数量不足!");
        //判断库存是否充足
        Validator.validateTrue(mtGoodsSku.getStock() >= obj.getBasketCount(), "商品库存数量不足!");
        //减少库存
     //   mtGoodsSku.setStock(mtGoodsSku.getStock() - obj.getBasketCount());
    //    Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存减少失败!");
        BeanUtil.copyProperties(obj, dogBasket);
        dogBasket.setUpdateTime(DateUtil.currentSeconds());
        dogBasket.setUpdateBy(SecurityUtils.getUser().getUserId());
        Validator.validateTrue(this.updateById(dogBasket), "修改库存失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 删除购物车
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(List<Long> ids) {
        // 判断是否为空
        Validator.validateTrue(CollUtil.isNotEmpty(ids), "主键标识为空");
        //查询所有
/*        List<MtBasket> list = CollUtil.newArrayList(this.listByIds(ids));
        list.forEach(e -> {
            //判断商品是否存在
            MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
          ///  Validator.validateNotNull(mtGoods, "商品不存在!");
            //判断SKU是否存在
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(e.getSkuId());
            Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
            //增加库存
          //  mtGoodsSku.setStock(mtGoodsSku.getStock() + e.getBasketCount());
         //   Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存增加失败!");
        });*/
        Validator.validateTrue(this.removeByIds(ids), "删除购物车失败!");
        return Boolean.TRUE;
    }
}
